package listeners;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JTextPane;
import view.Block;
import view.DrawPanel;
import view.EndBlock;
import view.PictureModel;
import view.StartBlock;

public class BlockMouseListener  extends MouseAdapter {
	private Block currentBlock;
	private DrawPanel paint;
	private PictureModel pictureModel;
	private ArrayList<JButton> buttons;
	private JTextPane textPane;

	public BlockMouseListener(DrawPanel paint, ArrayList<JButton> buttons,
			PictureModel pictureModel,JTextPane textPane) {
		this.paint = paint;
		this.buttons = buttons;
		this.pictureModel = pictureModel;
		this.textPane = textPane;
	}

	@Override
	public void mousePressed(MouseEvent event) {
		if (currentBlock != null) {
			Point point = event.getPoint();
			currentBlock.setPoint(point);
			if (currentBlock instanceof StartBlock || currentBlock instanceof EndBlock) {
				if(hasDublicate(currentBlock)){
					currentBlock = null;
					releaseAllButtons();
					textPane.setText("You have already  add Start or End block!!!");
					return;
				}
			}
			currentBlock.draw(paint.getGraphics2D());
			pictureModel.addBlock(currentBlock);
			currentBlock = null;
			releaseAllButtons();
			paint.repaint();
		}

	}

	public Block getCurrentBlock() {
		return currentBlock;
	}

	public void setCurrentBlock(Block currentBlock) {
		this.currentBlock = currentBlock;
	}

	private void releaseAllButtons() {
		for (JButton b : buttons) {
			b.setEnabled(true);
		}
	}
	private boolean hasDublicate(Block block){
		ArrayList<Block> blocks = pictureModel.getBlocks();
		for(Block b:blocks){
			if(b.getId()==block.getId())
				return true;
		}
		return false;
	}

}
